import { defineComponent, ref, watch, PropType } from 'vue';
/* components */
import NoDataViewNew from '@src/component/common/NoDataViewNew';
/* utils */
import dayjs from 'dayjs';
import { t } from '@src/locales';
import state from '@src/modules/intelligentQuality/utils/state.ts'
import {uuid} from '@src/util/lang/string.ts'
import { message, confirm } from '@src/util/message'
import { openAccurateTab } from '@src/util/platform'
/* type */
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
/* http */
import * as qualityApi from '@src/api/intelligentQuality.js'
/* scss*/
import '@src/modules/intelligentQuality/style/qualityTable.scss';

export default defineComponent({
  name: 'qualityTable',
  props: {
    loading: {
      type: Boolean,
      default: true
    },
    tableList: {
      type: Array as PropType<any>,
      default: () => ([])
    }
  },
  emit: ['delete', 'edit', 'goDetail'],
  setup(props, { emit }) {
    let pageSize = ref(30);
    let pageNum = ref(1);
    const total = ref<number>(0);
    const tableData = ref(props.tableList)
    const defaultTableData = {
      defaultPageSizes: [10, 20, 30, 40, 50, 100],
    };

    total.value = tableData.value.length;
    /**
     * @description 获取分页数据
     */
    const getPaginatedData = () => {
        const start = (pageNum.value - 1) * pageSize.value;
        const end = pageNum.value * pageSize.value;
        tableData.value = props.tableList.slice(start, end);
      };
    /**
     * @description 初始化分页参数
     */
    const initTableparams = () => {
        pageSize.value = 30;
        pageNum.value = 1;
        total.value = props.tableList.length;
    }

    watch(() => pageSize.value, () => getPaginatedData())
    watch(() => pageNum.value, () => getPaginatedData())

    watch(() => props.tableList, () => {
        initTableparams();
        getPaginatedData()
    }, { immediate: true })

    const currentChangeHandler = (val) => {
      pageNum.value = val
    }
    const sizeChangeHandler = (val) => {
      pageSize.value = val
    }

    return {
      total,
      tableData,
      pageSize,
      pageNum,
      defaultTableData,
      currentChangeHandler,
      sizeChangeHandler
    };
  },
  methods: {
    renderAction(row) {
      return (
        <div class={'qua-table-action'}>
          {
            state.auth.edit ? (
              <el-button type={'text'} onClick={() => this.$emit('edit', row.robotNo)}>编辑规则</el-button>
            ) : null
          }
          {
            state.auth.delete ? (
              <el-button type={'text'} onClick={() => this.$emit('delete', row.robotNo)}>{t('common.base.delete')}</el-button>
            ) : null
          }
        </div>
      );
    },
    handleSwitchChange(val: string, row: any) {
      qualityApi.switchRobot({robotNo: row.robotNo, enabled: val}).then(res => {
        if (!res.success) {
          message.error(res.message)
          return
        }
        if (val) {
          message.success("启用成功")
        } else {
          message.success("停用成功")
        }
        this.tableData = this.tableData.map(item => {
          if (item.robotNo === row.robotNo) {
            item.enabled = val
          }
          return item
        })
      })
      .catch(err => {
        message.error(err.message)
      })
    },
    /**
     * @description 点击跳转到详情页
     */
    // clickGoDetail(robotNo: string) {
    //   let fromId = window?.frameElement?.getAttribute('id')
    //   // 临时先这样
    //   openAccurateTab({
    //     type: PageRoutesTypeEnum.IntelligentQualityDetail,
    //     params: `robotNo=${robotNo}`,
    //     fromId
    //   })
    // }
  },
  render() {
    const directives = [{name: 'loading', value: this.loading}]
    return (
      <div class="qua-table" {...{directives}}>
        <div class="table">
          <el-table
            data={this.tableData}
            border={true}
            min-width={'100%'}
            height={'100%'}
            rowStyle={{ height: '64px' }}
            cellClassName={'qua-table-cell'}
            headerCellStyle={{ background: '#fafafa', color: '#262626' }}
            scopedSlots={{
              empty: ({ row }) => {
                return <NoDataViewNew />;
              },
            }}
          >
            <el-table-column
              label={'名称'}
              min-width={'160px'}
              show-overflow-tooltip={true}
              scopedSlots={{
                default: ({ row }) => {
                  return (<div class="qua-table-index table-blacklist">
                      <span class={'qua-table-name'} onClick={() => this.$emit('goDetail', row.robotNo)}>{row.name}</span>
                       <span class={'qua-table-remarks'}><span>{row.remarks}</span></span>
                  </div>);
                },
              }}
            />
            <el-table-column
              label={'编号'}
              min-width={'160px'}
              scopedSlots={{
                default: ({ row }) => {
                  return row.robotNo;
                },
              }}
            />
            <el-table-column
              label={'执行应用'}
              min-width={'160px'}
              scopedSlots={{
                default: ({ row }) => {
                  return row.formName || '';
                },
              }}
            />
            <el-table-column
              label={'质检字段'}
              min-width={'160px'}
              scopedSlots={{
                default: ({ row }) => {
                  return row.formField || '';
                },
              }}
            />
            <el-table-column
              label={'创建人'}
              min-width={'120px'}
              scopedSlots={{
                default: ({ row }) => {
                  return row.createUser.displayName || '';
                },
              }}
            />
            <el-table-column
              label={'创建时间'}
              min-width={'160px'}
              scopedSlots={{
                default: ({ row }) => {
                  let createTime = row.createTime;
                  createTime ? (createTime = dayjs(createTime).format('YYYY-MM-DD HH:mm:ss')) : ''
                  return createTime
                },
              }}
            />
            <el-table-column
              label={'启用'}
              min-width={'120px'}
              scopedSlots={{
                default: ({ row }) => {
                  const onSwitchChange = val => this.handleSwitchChange(val, row);
                  return (
                    <div class={'action'}>
                      {this.edit ? (
                        <el-switch active-value={true} inactive-value={false} key={uuid()} value={row.enabled} onChange={onSwitchChange} />
                      ) : (
                        <div class="group-action">
                          {
                            state.auth.edit ? (
                              <el-switch active-value={true} inactive-value={false} key={uuid()} value={row.enabled} onChange={onSwitchChange}></el-switch>
                            ) : (
                              <el-tooltip effect="dark" content={'你没有操作权限'} placement="top">
                                <el-switch active-value={true} inactive-value={false} key={uuid()} disabled={true} value={row.enabled} onChange={onSwitchChange}></el-switch>
                              </el-tooltip>
                            )
                          }
                            
                            {
                              row.enabled ? (
                                <span class="switch-base work">工作中</span>
                              ) : (
                                  <span class="switch-base disable">未启用</span>
                              )
                            }
                          </div>
                      )}
                    </div>
                  );
                },
              }}
            />
            <el-table-column
              label={'操作'}
              fixed={'right'}
              width={'140px'}
              scopedSlots={{
                default: ({ row }) => {
                  return this.renderAction(row);
                },
              }}
            />
          </el-table>
        </div>
        <div class={'qua-table-pagination'}>
          <div class="qua-table-pagination-total">
            {t('trigger.table.g')}&nbsp;<span>{this.total}</span>&nbsp;{t('trigger.table.t')}
          </div>
          <el-pagination class="table-pagination" background 
          currentPage={this.pageNum} 
          pageSize={this.pageSize} 
          pageSizes={this.defaultTableData.defaultPageSizes} 
          layout={'prev, pager, next, sizes, jumper'} 
          total={this.total} 
          onCurrent-change={val => this.currentChangeHandler(val)} 
          onSize-change={val => this.sizeChangeHandler(val)}></el-pagination>
        </div>
      </div>
    );
  },
});
